<script>
import {uploadFile} from "../../../static/utils/uploadImg";

export default {
  name: "index",
  emit: ['change', 'input', 'delete'],
  props: {
    value: {
      type: [String, Object],
      default: '',
    },
    url: {
      type: String,
      default: 'common/upload',
    },
    accept: {
      type: String,
      default: 'image',
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      list: [],
    }
  },
  watch: {
    value: {
      handler(val) {
        if (val) {
          this.list = [{
            url: val,
            status: 'success',
            message: '上传成功'
          }]
        }
      },
      immediate: true
    }
  },
  methods: {
    // 公共图片上传
    async uploadImg(event, key) {
      const file = event.file;
      this.list.push({
        ...file,
        status: 'uploading',
        message: '上传中'
      })
      console.log(file, '开始上传')
      uploadFile(this.$props.url, file).then( res => {
        console.log('上传成功')
        let data = JSON.parse(res.data);
        data = data.data || data;
        this.list.splice(0, 1, Object.assign(this.list[0], {
          status: 'success',
          message: '上传成功',
          url: data.fullPath
        }))
        this.$emit('input', data.fullPath)
        this.$emit('change', data.fullPath, data);
      })
    },
    deleteImg(name) {
      this.list = []
      this.$emit('delete', name)
      this.$emit('input', '')
      // this.$emit('change', data.fullPath, data);
    },
  },
}
</script>

<template>
  <view>
    <u-upload
        :fileList="list"
        name="1"
        :maxCount="1"
        :accept="accept"
		width="75"
		height="75"
        @afterRead="(event) => { uploadImg(event, 'roofPhotoOne') }"
        @delete="deleteImg('roofPhotoOne')"
        :disabled="disabled"
        :deletable="!disabled"
    >
      <!--slot-->
      <slot>
        <view class="upload-cover">
          <u-icon class="upload-cover__icon" name="camera-fill" size="25" color="#bbb"></u-icon>
        </view>
      </slot>
    </u-upload>
  </view>
</template>

<style scoped lang="scss">
.upload-cover{
  position: relative;
  //width: 80px;
  //height: 80px;
  max-width: 75px;
  display: inline-block !important;
  padding: 25px;
  background: #f5f5f5;
  //&__icon{
  //  position: relative;
  //  top: 50%;
  //  left: 50%;
  //  transform: translate(-50%, -50%);
  //}
}
</style>
